﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace System.Web.Mvc.Ajax
{
    /// <summary>
    /// 上一页、下一页分页方式的Ajax分页控件生成类
    /// </summary>
    public class AjaxPrevNextPaggerFormat : AjaxPaggerFormat
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="options">AjaxHelper.AjaxOptions对象</param>
        public AjaxPrevNextPaggerFormat(AjaxOptions options)
            : base(options)
        {
            this.FirstLabel = "first";
            this.PreviousLabel = "previous";
            this.NextLabel = "next";
            this.LastLabel = "last";
        }

        /// <summary>
        /// 首页按钮Label,默认值：first
        /// </summary>
        public string FirstLabel { get; set; }

        /// <summary>
        /// 上一页按钮Label,默认值：previous
        /// </summary>
        public string PreviousLabel { get; set; }

        /// <summary>
        /// 下一页按钮Label，默认值：next
        /// </summary>
        public string NextLabel { get; set; }

        /// <summary>
        /// 尾页按钮Label,默认值：last
        /// </summary>
        public string LastLabel { get; set; }

        /// <summary>
        /// 生成HttpGet方式的分页控件
        /// </summary>
        /// <param name="actionName">获取分页数据的Action Name</param>
        /// <param name="controllerName">获取分页数据的Controller Name</param>
        /// <param name="routeValues">获取分页数据的路由参数</param>
        /// <param name="rowCount">分页的总行数</param>
        /// <param name="pageIndex">当前分页索引，从0开始</param>
        /// <param name="pageSize">每页显示个数</param>
        /// <returns></returns>
        public override string GenerateGetFormatString(string actionName, string controllerName, RouteValueDictionary routeValues, int rowCount, int pageIndex, int pageSize)
        {
            int pageCount = pageSize != 0 ? (rowCount % pageSize == 0 ? rowCount / pageSize : rowCount / pageSize + 1) : 0;
            if (pageCount <= 1)
            {
                return String.Empty;
            }
            UrlHelper urlHelper = new UrlHelper(this.Helper.ViewContext.RequestContext);
            string formAction = urlHelper.Action(actionName, controllerName, routeValues);
            formAction = urlHelper.Content(formAction);
            StringBuilder sb = new StringBuilder();
            using (AjaxForm form = new AjaxForm(this.Helper, formAction, this.Options, null, sb, false))
            {

                form.BeginChild("script", new Dictionary<string, string>() {
                    { "type", "text/javascript" }
                });

                form.AppendHtml(GeneratePageButtonJavascriptEvents(form.FormId, pageCount));

                form.EndChild("script");

                form.AppendChild("input", new Dictionary<string, string>() { 
                    { "type", "hidden" }, 
                    { "name", "pageIndex" },
                    { "value", pageIndex.ToString() }
                });

                HttpRequest request = System.Web.HttpContext.Current.Request;
                if (request.Form.HasKeys())
                {
                    foreach (string key in request.Form.Keys)
                    {
                        if (key != "pageIndex")
                        {
                            form.AppendChild("input", new Dictionary<string, string>() { 
                                { "type", "hidden" }, 
                                { "name", key },
                                { "value", request[key] }
                            });
                        }
                    }
                }

                form.AppendChild("input", new Dictionary<string, string>() {
                    { "type", "button" },
                    { "value", this.FirstLabel },
                    { "disabled", "disabled" },
                    { "onclick", form.FormId+"_pagger.forwardToFirst();" }
                });
                form.AppendChild("input", new Dictionary<string, string>() {
                    { "type", "button" },
                    { "value", this.PreviousLabel },
                    { "disabled", "disabled" },
                    { "onclick", form.FormId+"_pagger.forwardToPrevious();" }
                });

                form.AppendHtml(String.Format("<span>{0}/{1}</span>", pageIndex + 1, pageCount));

                form.AppendChild("input", new Dictionary<string, string>() {
                    { "type", "button" },
                    { "value", this.NextLabel },
                    { "onclick", form.FormId+"_pagger.forwardToNext();" }
                });
                form.AppendChild("input", new Dictionary<string, string>() {
                    { "type", "button" },
                    { "value", this.LastLabel },
                    { "onclick", form.FormId+"_pagger.forwardToLast();" }
                });
            }

            return sb.ToString();
        }

        /// <summary>
        /// 生成HttpPost方式的分页控件
        /// </summary>
        /// <param name="actionName">获取分页数据的Action Name</param>
        /// <param name="controllerName">获取分页数据的Controller Name</param>
        /// <param name="routeValues">获取分页数据的路由参数</param>
        /// <param name="rowCount">分页的总行数</param>
        /// <param name="pageIndex">当前分页索引，从0开始</param>
        /// <param name="pageSize">每页显示个数</param>
        /// <returns></returns>
        public override string GeneratePostFormatString(string actionName, string controllerName, RouteValueDictionary routeValues, int rowCount, int pageIndex, int pageSize)
        {
            return GenerateGetFormatString(actionName, controllerName, routeValues, rowCount, pageIndex, pageSize);
        }

        private string GeneratePageButtonJavascriptEvents(string formId, int pageCount)
        {

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("var " + formId + "_pagger = {");
            sb.AppendLine(" forwardToFirst: function() {");
            sb.AppendLine("     $('#" + formId + "').find(':hidden[name=pageIndex]:first').val('0');$('#" + formId + "').submit();");
            sb.AppendLine("     $('#" + formId + " span:first').text('1/" + pageCount + "');");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.FirstLabel + "\"]').attr('disabled', true);");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.PreviousLabel + "\"]').attr('disabled', true);");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.NextLabel + "\"]').attr('disabled', false);");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.LastLabel + "\"]').attr('disabled', false);");
            sb.AppendLine(" },");
            sb.AppendLine(" forwardToPrevious: function() {");
            sb.AppendLine("     var $_pageIndex_$ = $('#" + formId + "').find(':hidden[name=pageIndex]:first').val();");
            sb.AppendLine("     if (!isNaN($_pageIndex_$)) { $_pageIndex_$ = parseInt($_pageIndex_$) - 1; } else { $_pageIndex_$ = 0; } ");
            sb.AppendLine("     $('#" + formId + "').find(':hidden[name=pageIndex]:first').val($_pageIndex_$);$('#" + formId + "').submit();");
            sb.AppendLine("     var disabled = $_pageIndex_$ < 1;");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.FirstLabel + "\"]').attr('disabled', disabled);");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.PreviousLabel + "\"]').attr('disabled', disabled);");
            sb.AppendLine("     disabled = $_pageIndex_$ >= " + (pageCount - 1) + ";");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.NextLabel + "\"]').attr('disabled', disabled);");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.LastLabel + "\"]').attr('disabled', disabled);");
            sb.AppendLine("     var s = ($_pageIndex_$ + 1).toString() + '/' + " + pageCount + ";");
            sb.AppendLine("     $('#" + formId + " span:first').text(s);");
            sb.AppendLine(" },");
            sb.AppendLine(" forwardToNext: function() {");
            sb.AppendLine("     var $_pageIndex_$ = $('#" + formId + "').find(':hidden[name=pageIndex]:first').val();");
            sb.AppendLine("     if (!isNaN($_pageIndex_$)) { $_pageIndex_$ = parseInt($_pageIndex_$) + 1; } else { $_pageIndex_$ = 0; } ");
            sb.AppendLine("     $('#" + formId + "').find(':hidden[name=pageIndex]:first').val($_pageIndex_$);$('#" + formId + "').submit();");
            sb.AppendLine("     var disabled = $_pageIndex_$ < 1;");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.FirstLabel + "\"]').attr('disabled', disabled);");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.PreviousLabel + "\"]').attr('disabled', disabled);");
            sb.AppendLine("     disabled = $_pageIndex_$ >= " + (pageCount - 1) + ";");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.NextLabel + "\"]').attr('disabled', disabled);");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.LastLabel + "\"]').attr('disabled', disabled);");
            sb.AppendLine("     var s = ($_pageIndex_$ + 1).toString() + '/' + " + pageCount + ";");
            sb.AppendLine("     $('#" + formId + " span:first').text(s);");
            sb.AppendLine(" },");
            sb.AppendLine(" forwardToLast: function() {");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.FirstLabel + "\"]').attr('disabled', false);");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.PreviousLabel + "\"]').attr('disabled', false);");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.NextLabel + "\"]').attr('disabled', true);");
            sb.AppendLine("     $('#" + formId + " :button[value=\"" + this.LastLabel + "\"]').attr('disabled', true);");
            sb.AppendLine("     $('#" + formId + "').find(':hidden[name=pageIndex]:first').val('" + (pageCount - 1) + "');$('#" + formId + "').submit();");
            sb.AppendLine("     $('#" + formId + " span:first').text('" + pageCount + "/" + pageCount + "');");
            sb.AppendLine(" }");
            sb.AppendLine("};");

            return sb.ToString();
        }
    }
}
